/*
 * Copyright (c) 2015 Uwantsoft Ltd.
 * www.uwantsoft.com
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Uwantsoft ("Confidential Information").
 * You shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement you
 * entered into with Uwantsoft.
 */

package com.uwantsoft.util;

import com.uwantsoft.business.service.domain.user.Driver;
import org.hibernate.annotations.Generated;
import org.hibernate.annotations.GenerationTime;
import org.hibernate.annotations.Type;
import org.joda.time.DateTime;

import javax.persistence.*;

/**
 * @author Chuanbao
 */
@MappedSuperclass
public abstract class AbstractEntity {
    @Id
    @GeneratedValue
    private Integer id;

    @Column
    @Version
    private Integer version;

    @Column
    private Boolean active = Boolean.TRUE;

    @Column
    private String guid = GuidGenerator.generateGuid();

    @Column(name = "create_time", columnDefinition = "datetime")
    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
    private DateTime createTime = JodaUtils.now();

    @Column(name = "last_modify_time", columnDefinition = "timestamp default now() on update now()")
    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
    @Generated(GenerationTime.ALWAYS)
    private DateTime lastModifyTime = JodaUtils.now();

    public String guid() {
        return this.guid;
    }


    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof AbstractEntity)) {
            return false;
        }
        AbstractEntity that = (AbstractEntity) o;
        return guid().equals(that.guid());
    }

    @Override
    public int hashCode() {
        return guid().hashCode();
    }

    public void active(boolean active) {
        this.active = active;
    }

    public DateTime createTime() {
        return createTime;
    }

    /**
     * Only for unit test
     * todo:have a system properties to identify if the environment is unittest or web
     *
     * @param createTime
     */
    public void createTime(DateTime createTime) {
        this.createTime = createTime;
    }

    public int version() {
        return version;
    }

    public DateTime lastModifyTime() {
        return lastModifyTime;
    }

    public Boolean active() {
        return active;
    }

    public void lock(boolean lock) {
        this.active(!lock);
    }
}